package com.yupi.yupicturebackend.api.aliyunai;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.yupi.yupicturebackend.api.aliyunai.model.outPainting.CreateOutPaintingTaskRequest;
import com.yupi.yupicturebackend.api.aliyunai.model.outPainting.CreateOutPaintingTaskResponse;
import com.yupi.yupicturebackend.api.aliyunai.model.outPainting.GetOutPaintingTaskResponse;
import com.yupi.yupicturebackend.api.aliyunai.model.test2Image.CreateText2ImageRequest;
import com.yupi.yupicturebackend.api.aliyunai.model.test2Image.CreateText2ImageResponse;
import com.yupi.yupicturebackend.api.aliyunai.model.test2Image.GetText2ImageResponse;
import com.yupi.yupicturebackend.exception.BusinessException;
import com.yupi.yupicturebackend.exception.ErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class AliYunAiApi {
    // 读取配置文件
    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    // 创建任务地址
    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";

    // 查询任务状态
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";



    /**
     * 创建任务
     *
     * @param createOutPaintingTaskRequest
     * @return
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        if (createOutPaintingTaskRequest == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "扩图参数为空");
        }
        // 发送请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                // 必须开启异步处理，设置为enable。
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("请求异常：{}", httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图失败");
            }
            CreateOutPaintingTaskResponse response = JSONUtil.toBean(httpResponse.body(), CreateOutPaintingTaskResponse.class);
            String errorCode = response.getCode();
            if (StrUtil.isNotBlank(errorCode)) {
                String errorMessage = response.getMessage();
                log.error("AI 扩图失败，errorCode:{}, errorMessage:{}", errorCode, errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图接口响应异常");
            }
            return response;
        }
    }

    /**
     * 查询创建的任务
     *
     * @param taskId
     * @return
     */
    public GetOutPaintingTaskResponse getOutPaintingTask(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务 id 不能为空");
        }
        try (HttpResponse httpResponse = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .execute()) {
            if (!httpResponse.isOk()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取任务失败");
            }
            return JSONUtil.toBean(httpResponse.body(), GetOutPaintingTaskResponse.class);
        }
    }


    // 文本生成图片任务地址
    public static final String CREATE_TEXT_TO_IMAGE_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis";
    /**
     * 创建文本生成图片任务
     * @param request 请求参数
     * @return 任务创建响应
     */
    public CreateText2ImageResponse createTextToImageTask(CreateText2ImageRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "文本生成图片参数为空");
        }

        // 发送请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_TEXT_TO_IMAGE_TASK_URL)
                .header("X-DashScope-Async", "enable") // 必须开启异步
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .header(Header.CONTENT_TYPE, ContentType.JSON.getValue())
                .body(JSONUtil.toJsonStr(request));

        try (HttpResponse httpResponse = httpRequest.execute()) {
            if (!httpResponse.isOk()) {
                log.error("文本生成图片请求异常：{}", httpResponse.body());
                CreateText2ImageResponse response = JSONUtil.toBean(httpResponse.body(), CreateText2ImageResponse.class);

                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 文本生成图片失败");
            }

            CreateText2ImageResponse response = JSONUtil.toBean(httpResponse.body(), CreateText2ImageResponse.class);

            String errorCode = response.getCode();
            if (StrUtil.isNotBlank(errorCode)) {
                String errorMessage = response.getMessage();
                log.error("AI 文本生成图片失败，errorCode:{}, errorMessage:{}",errorCode, errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 文本生成图片接口响应异常");

            }

            return response;
        } catch (Exception e) {
            log.error("文本生成图片请求异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文本生成图片请求异常");
        }
    }

    /**
     * 查询文本生成图片任务状态
     * @param taskId 任务ID
     * @return 任务状态响应
     */
    public GetText2ImageResponse getTextToImageTask(String taskId) {
        if (StrUtil.isBlank(taskId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "任务ID不能为空");
        }

        try (HttpResponse httpResponse = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + apiKey)
                .execute()) {

            if (!httpResponse.isOk()) {
                log.error("查询任务状态失败，状态码：{}，响应：{}",
                        httpResponse.getStatus(), httpResponse.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取文本生成图片任务失败");
            }
//            GetText2ImageResponse bean = JSONUtil.toBean(httpResponse.body(), GetText2ImageResponse.class);

            return JSONUtil.toBean(httpResponse.body(), GetText2ImageResponse.class);
        } catch (Exception e) {
            log.error("查询文本生成图片任务异常", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "查询文本生成图片任务异常");
        }
    }
}
